﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace StandardInterface
{
    public class GetRequestinfo
    {
        // 模拟缓存服务
        private static readonly Dictionary<string, string> SYSTEM_CACHE = new Dictionary<string, string>();

        // ecology 系统发放的授权许可证(appid)
        private static readonly string APPID = "EEAA5436-7577-4BE0-8C6C-89E9D44801EA";

        private static readonly HttpClient httpClient = new HttpClient();

        public static async Task Test()
        {
            string reqeustids = "1304197";
            string userid = "23844";

            string spk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmIqeh3HlAxMNSjepuY1YsRj6pqfX/r88v1xOKI7+vIXDpMLgmaA8ytRGTyHaxscXiXxcCKE6T+z54qrxaxw6b4/WSfcH8QaghHhQRAtvMWxP/SC1Vg5dniQMUVvrsB2wbf0DfyiftGeBf8gJbe1uWsXrMZLZE3olrDMCjylo8SwIDAQAB";

            SYSTEM_CACHE["SERVER_PUBLIC_KEY"] = spk;

            //string[] requestid = reqeustids.Split(',');
            // string[] userid = userids.Split(',');
            await TestRestful(userid);

            //for (int i = 0; i < requestid.Length; i++)
            //{
            //    Console.WriteLine(requestid[i] + "   " + userid[i]);
            //    string param = "requestId=" + requestid[i];
            //    await TestRestful("http://oa.maxwell-gp.com.cn:8090", "/api/workflow/paService/getWorkflowRequest", param, userid[i]);
            //}
        }

        public static async Task Main(string[] args)
        {
            await Test();
        }

        /// <summary>
        /// 第一步：调用 ecology 注册接口,根据 appid 进行注册,将返回服务端公钥和 Secret 信息
        /// </summary>
        //public static async Task<Dictionary<string, object>> TestGetoken(string address)
        //{
        //    // 从系统缓存或者数据库中获取 ECOLOGY 系统公钥和 Secret 信息
        //    string secret = "6a393956-42c1-4b75-8b77-91c342ed90f1";
        //    string spk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmIqeh3HlAxMNSjepuY1YsRj6pqfX/r88v1xOKI7+vIXDpMLgmaA8ytRGTyHaxscXiXxcCKE6T+z54qrxaxw6b4/WSfcH8QaghHhQRAtvMWxP/SC1Vg5dniQMUVvrsB2wbf0DfyiftGeBf8gJbe1uWsXrMZLZE3olrDMCjylo8SwIDAQAB";

        //    SYSTEM_CACHE["SERVER_PUBLIC_KEY"] = spk;
        //    SYSTEM_CACHE["SERVER_SECRET"] = secret;

        //    // 对秘钥进行加密传输，防止篡改数据
        //    string encryptSecret = RSAEncrypt(secret, spk);

        //    // 调用 ECOLOGY 系统接口进行注册
        //    var request = new HttpRequestMessage(HttpMethod.Post, address + "/api/ec/dev/auth/applytoken");
        //    request.Headers.Add("appid", APPID);
        //    request.Headers.Add("secret", encryptSecret);
        //    request.Headers.Add("time", "3600");

        //    var response = await httpClient.SendAsync(request);
        //    string data = await response.Content.ReadAsStringAsync();

        //    Console.WriteLine("TestGetoken()：" + data);

        //    var datas = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);

        //    // ECOLOGY 返回的 token
        //    string token = datas.ContainsKey("token") ? datas["token"]?.ToString() ?? "" : "";
        //    SYSTEM_CACHE["SERVER_TOKEN"] = token;

        //    return datas;
        //}

        public static async Task<string> TestRestful(string userid)
        {

            string spk = SYSTEM_CACHE.ContainsKey("SERVER_PUBLIC_KEY") ? SYSTEM_CACHE["SERVER_PUBLIC_KEY"] : "";
            // 对用户信息进行加密传输
            string encryptUserid = RSAEncrypt(userid, spk);
            Console.WriteLine("加密后的userid:" + encryptUserid);
            return encryptUserid;



        }

        /// <summary>
        /// 使用RSA公钥加密数据（支持X.509格式公钥）
        /// </summary>
        static string RSAEncrypt(string data, string publicKey)
        {
            try
            {
                // 将Base64公钥转换为字节数组
                byte[] publicKeyBytes = Convert.FromBase64String(publicKey);

                using (RSA rsa = RSA.Create())
                {
                    // 导入X.509格式的公钥
                    rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);

                    // 加密数据，使用PKCS#1填充
                    byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                    byte[] encryptedBytes = rsa.Encrypt(dataBytes, RSAEncryptionPadding.Pkcs1);

                    return Convert.ToBase64String(encryptedBytes);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"RSA加密失败: {ex.Message}");
                Console.WriteLine($"StackTrace: {ex.StackTrace}");
                return null;
            }
        }
    }
}